<template>
    <div class="detailContainer bg-gray">
        <!-- 生成首页>服务产品详情，首页可点击 -->
        <div class="row-spaceb-col-center">
            <div class="pt20"><strong class="showMouse fwbold" @click="gotioHome">首页</strong> > 服务产品详情</div>
            <div><el-button type="primary" plain size="small" @click="goBack" >返回</el-button></div>
        </div>
        <div class="width-24 row-start mt20">
             <div class="width-17 custom-card mr20 relposition">
                 <div class="absposition badge">
                    <img v-if="product.parentProductTypeId === '1'" src="~@/assets/image/badge.png" style="width:92px;height:28px" alt="">
                    <img v-if="product.parentProductTypeId === '2'" src="~@/assets/image/badge2.png" style="width:92px;height:28px" alt="">
                 </div>
                 <div class="row-spaceb">
                    <div class="width-12 pd30 mr20">
                        <!-- 使用elementUI组件展示产品轮播图 -->
                            <el-carousel indicator-position="outside">
                                <el-carousel-item v-for="(item,index) in product?.images" :key="index">
                                        <img :src="`/api/public/file/v1/public/get/${item}`" style="width:100%;max-width:100%; max-height:100%; object-fit:contain;"  @error="setDefaultImage" />
                                </el-carousel-item>
                            </el-carousel>
                            <div class="color-grey fs14 row-center">
                                <!-- <span>满意率：{{product?.satisfactionRate || '-'}}</span> -->
                                <span class="ml30">访问次数：{{product?.accessNum}}</span>
                                <span class="ml30">申请次数：{{product?.transNum}}</span>
                            </div>
                    </div>
                    <div class="width-12 pt30 pr30 pl10 color-grey">
                        <div class="product-title">{{product?.productName}}</div>
                        <!-- Only show market and platform prices for parentProductTypeId !== 2 -->
                        <template v-if="product.parentProductTypeId !== '2'">
                            <div class="mt10">市场指导价:<span style="text-decoration: line-through">{{$priceFormat(product?.limitMarketGuidancePrice,product?.upperMarketGuidancePrice)}}</span>元</div>
                            <div v-if="product.limitDiscount > 0">
                                <div class="mt10">平台销售价:<span style="text-decoration: line-through">{{$priceFormat(product?.limitOriginalPrice,product?.upperOriginalPrice)}}</span>元</div>
                                <div class="row-spaceb mt10">
                                    <div>券后价:<span class="fs20 color-red fwbold">{{$priceFormat(product?.limitPrice, product?.upperPrice)}} 元</span></div>
                                </div>
                            </div>
                            <div v-else>
                                <div class="mt10">平台销售价:<span class="fs20 color-red fwbold">{{$priceFormat(product?.limitOriginalPrice,product?.upperOriginalPrice)}}</span>元</div>
                            </div>
                        </template>
                        <!-- Show only "面议" for parentProductTypeId === 2 -->
                        <template v-else>
                            <div class="mt10 row-spaceb">
                                <div>券后价: <span class="fs20 color-red fwbold">面议</span></div>
                                <div v-if="product.productTypeName.includes('设备租赁')">当期LPR: <span class="fs16 color-red fwbold">{{currentLpr}}</span></div>
                            </div>
                        </template>
                        <div class="mt10">服务类型: <span class="color-text">
                            {{product?.productTypeName}}
                            <template v-if="product?.productTypeName?.includes('数字化转型')">
                                {{product.digitalSubtype ? ' - ' + getCommonDictLabel(product.digitalSubtype, 'digital_subtype') : ''}}
                                {{product.digitalIndustry ? ' - ' + getCommonDictLabel(product.digitalIndustry, 'digital_industry') : ''}}
                                {{product.digitalScenarios ? ' - ' + getScenarioLabels(product.digitalScenarios) : ''}}
                            </template>
                        </span></div>
                        <!-- 写一个html,一个小方框，左侧是图片，右侧是券产品剩余，券的有效期 -->
                            <div v-if="product.limitDiscount > 0 || product.parentProductTypeId == 2"
                                 :class="[product.parentProductTypeId == 1 ? 'quancard' : 'quancard1', 'mt10 pd10 pt20 fs16']">
                                    <div style="font-size: 16px;color: #292929;">最高补贴：
                                        <span class="fs18 color-red fwbold">
                                            <template v-if="product.productTypeName?.includes('融资担保')">
                                                实际担保费用的50%
                                            </template>
                                            <template v-else-if="product.productTypeName?.includes('设备租赁')">
                                                当期LPR的20%
                                            </template>
                                            <template v-else>
                                                ↓{{$priceFormat(product.limitDiscount,product.upperDiscount)}} 元
                                            </template>
                                        </span>
                                    </div>
                                    <div class="mt10 fs14">用券有效期：<span class="color-red fwbold">{{product?.voucherValidBeginTime | timeFilter}} ~ {{product?.voucherValidEndTime | timeFilter}}</span></div>
                            </div>
                            <!-- <div v-else style="height:86px"></div> -->
                            <!-- 写两个按钮并排放，一个是加入收藏，一个是申请服务，两个按钮的样式不同 -->
                            <div class="row-spaceb mt20">
                                <el-button type="primary" @click="addSave" class="button1 width-11">加入收藏</el-button>
                                <el-button type="success" @click="submitOrder" class="button2 width-11">申请服务</el-button>
                            </div>
                    </div>
                 </div>
             </div>
             <div class="width-7 custom-card pd30">
                    <div class="color-grey">
                        <div class="companyContain">
                            <img :src="`/api/public/file/v1/public/get/${product?.serviceInfo?.companyLogo}`" alt="" class="smallIcon">
                            <div class="ml20">
                                <div class="fs18 fwbold color-black">{{product?.serviceInfo?.companyName}}</div>
                                <div class="mt10">拥有<span class="color-red">{{product?.serviceInfo?.productCount}}</span>个产品</div>
                                <div class="mt10">服务电话:{{product?.contactPhoneNum}}({{product?.contactPerson}})</div>
                            </div>
                        </div>
                        <div class="mt30">服务商地址</div>
                        <div class="mt10">{{product?.serviceInfo?.companyAddress}}</div>
                        <div class="mt10">工作时间</div>
                        <div class="mt10">{{ workDate(product?.serviceInfo?.workDate) }} {{product?.serviceInfo?.workBeginTime}}-{{product?.serviceInfo?.workEndTime}}</div>
                    </div>
                    <div class="mt20 row-center">
                        <el-button @click="gotoCompanyDetail(product?.serviceInfo)" class="button3 width-24" >机构详情</el-button>
                    </div>
             </div>
        </div>
         <!-- 使用el-tab 实现服务详情和服务评价两个标签页切换 -->
        <el-card class="mt20">
            <el-tabs v-model="activeName" class="bg-white pt10" @tab-click="handleClick">
                <el-tab-pane label="服务详情" name="first">
                    <div class="pl40 pr40 pt10 pb40">
                         <div class="row-start">
                            <div class="left-border"></div>
                            <div class="ml5 fs16 fwbold">产品简介</div>
                        </div>
                        <div style="white-space:pre-wrap;text-indent: 2em;line-height:24px" v-html="product.serviceContent" class="fs16 mt10"></div>
                        <div v-if="product.advantage && product.parentProductTypeId !== '2'" class="row-start mt30">
                            <div class="left-border"></div>
                            <div class="ml5 fs16 fwbold">服务典型案例</div>
                        </div>
                        <div style="white-space:pre-wrap;line-height:24px" v-html="product.advantage" class="fs16 mt10"></div>
                        <div class="row-start mt30">
                            <div class="left-border"></div>
                            <div class="ml5 fs16 fwbold">服务详情介绍</div>
                        </div>
                        <div v-html="product.productDetail" class="fs16 mt10 rich-text-content"></div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="服务评价" name="second">
                    <div class="pl40 pr40 pb40">
                        <template>
                            <!-- <div>
                                <el-radio-group v-model="activeStar" size="mini" class="mb30" @input="selectStar">
                                    <el-radio-button label="all">全部</el-radio-button>
                                    <el-radio-button v-for="star in [5, 4, 3, 2, 1]" :label="star"  :key="star">{{`${star} 星`}}</el-radio-button>
                                </el-radio-group>
                            </div> -->
                            <div v-if="reviews.length > 0">
                                <div v-if="activeStar === 'all'">
                                    <div v-for="(review, index) in reviews" :key="index">
                                        <div class="row-spaceb-col-center">
                                            <div class="row-start-col-center">
                                                <img src="@/assets/image/avatar.png" style=" width:30px;height:30px" alt="">
                                                <p class="ml10">{{ review.companyName }}</p>
                                            </div>
                                             <div class="color-grey fs14">
                                                 {{ review.createTime | timeFilter }}
                                            </div>
                                        </div>
                                        <!-- <el-rate v-model="review.starNum" disabled :colors="['#F56C6C','#F56C6C','#F56C6C','#F56C6C','#F56C6C']"></el-rate> -->
                                        <div>{{ review.comment }}</div>
                                        <el-divider v-if="index!==(reviews.length - 1)"></el-divider>
                                    </div>
                                </div>
                                <div v-else>
                                    <div v-for="(review, index) in filteredReviews(activeStar)" :key="index">
                                    <div class="row-start-col-center">
                                            <img src="@/assets/image/avatar.png" style=" width:30px;height:30px" alt="">
                                            <p class="ml10">{{ review.companyName }}</p>
                                        </div>
                                        <el-rate v-model="review.score" disabled :colors="['#F56C6C','#F56C6C','#F56C6C','#F56C6C','#F56C6C']"></el-rate>
                                        <div>{{ review.comment }}</div>
                                        <el-divider v-if="index!==(reviews.length - 1)"></el-divider>
                                    </div>
                                </div>
                            </div>
                            <div v-else>
                                <el-empty :image-size="200" description="暂无评价"></el-empty>
                            </div>
                        </template>
                    </div>
                </el-tab-pane>
            </el-tabs>
       </el-card>
    </div>
</template>

<script>
import { getProductDetail,productCollect,evaluatePage,getCurrentLpr } from '@/api/homeApi'
import moment from 'moment';
import { workDate } from '@/utils/index'
export default {
    name: 'ProductDetail',
    filters: {
        timeFilter: function (value) {
            if(!value) {
              return '';
            }else{
              return moment(value).format('yyyy年MM月DD日');
            }
        }
    },
    data() {
        return {
            workDate,
            activeStar: 'all',
            productId: '',
            reviews: [],
            activeName: 'first',
            product: {
                productName: '产品名称',
                price: 100,
                description: '企达分销DRP标准是企达软件自主研发的一款针对小、中大型企业的一套B/S架构企业管理软件，主要以进销存及妓流管理为一休的管理软件，集进物存、财务、分销、OA管理为一依,通过tntenet，企业总部与分支机构《门店、办事处、经销刻)在同一平台上协同办公，实现了对整个企业范围内销售、库存、费用、办公等信息的全方位实时管理掌控，为企业决策提供最重要的数据和速度，为企业进一步扩张和更快的发展打下坚实的基础。帮助企业建立起一个简捷、高效的实时运营管理平台，解决企业的异地分支机构集中统—管理问题',
                images: [
                    require('@/assets/image/productBg.png'),
                    require('@/assets/image/productBg.png'),
                    require('@/assets/image/productBg.png')
                ]
            },
            currentLpr: 0,
            digitalSubtypeOptions: [],
            digitalIndustryOptions: [],
            digitalScenariosOptions: []
        }
    },
    mounted() {
        // Fetch product data from API and assign it to the 'product' data property
        this.fetchProductData();
        // 获取路由query的产品id
        this.productId = this.$route.query?.id;
        if(this.productId){
            this.getProductDetail(this.productId)
            this.getevaluatePage()
            this.getCurrentLpr()
        }

        // 添加字典初始化
        if (this.commonDict.length === 0) {
            this.$store.dispatch('getCommonDict').then(() => {
                this.initDigitalOptions();
            })
        } else {
            this.initDigitalOptions();
        }
    },
    computed: {
        starCounts() {
        const counts = { 5: 0, 4: 0, 3: 0, 2: 0, 1: 0 };
        for (const review of this.reviews) {
            counts[review.rate]++;
        }
        return counts;
        },
        commonDict() {
            return this.$store.state.common.commonDict;
        }
    },
    methods: {
        getCurrentLpr(){
            getCurrentLpr().then(res => {
                if(res.code === 200){
                    let lprObj = res.data
                    if(lprObj.yearOne){
                        this.currentLpr = (lprObj.yearOne / 100).toFixed(2) + '%(一年期)'
                    }else{
                        this.currentLpr = '3.1%(一年期)'
                    }
                }
            })
        },
        goBack() {
            // Navigate back to the previous page
            this.$router.go(-1);
        },
        selectStar(star) {
            console.log('start',star)
            let starNum = ''
            if(star === 'all') {
              starNum = '';
            } else {
                starNum = star;
            }
            evaluatePage({productId:this.productId,pageNo:1,pageNum:10,starNum}).then(res => {
                if(res.code == 200){
                    this.reviews = res.rows
                }
            })
        },
        setDefaultImage(event) {
            event.target.src = require('@/assets/image/error.jpg');
        },
        handleClick() {
            // Handle tab click event
        },
        getevaluatePage(){
            evaluatePage({productId:this.productId,pageNo:1,pageNum:10}).then(res => {
                if(res.code == 200){
                    this.reviews = res.rows
                }
            })
        },
        getProductDetail(productId){
            getProductDetail({productId}).then(res => {
                if(res.code == 200){
                    this.product = res.data
                    this.product.images = this.product.productImg.includes('|') ? this.product.productImg.split('|') : [this.product.productImg];
                }
            })
        },
        filteredReviews(star) {
              return this.reviews.filter(review => review.starNum === star);
        },
        gotioHome() {
            // Navigate to the home page
            this.$router.push({ path: '/index' });
        },
        addSave() {
            // Add the product to the user's saved products
            productCollect({productId:this.productId}).then(res => {
                if(res.code == 200){
                    this.$message.success('收藏成功')
                }
            })
        },
        submitOrder() {
            // Request the service associated with the product
            this.$router.push({ path: '/submitOrder',query:{id:this.productId} });
        },
        gotoCompanyDetail(com) {
            // Navigate to the company detail page
            this.$router.push({ path: '/companyDetail',query:{id:com.companyId} });
        },
        fetchProductData() {
            // Make an API request to fetch the product data
            // Assign the response to the 'product' data property
        },
        getScenarioLabels(scenarios) {
            if (!scenarios) return '';
            const scenarioArray = scenarios.includes(',') ? scenarios.split(',') : [scenarios];
            return scenarioArray
                .map(item => this.getCommonDictLabel(item, 'digital_scenarios'))
                .filter(Boolean)
                .join('、');
        },
        getCommonDictLabel(value, type) {
            if (!value) return '';
            const options = type === 'digital_subtype' ? this.digitalSubtypeOptions :
                           type === 'digital_industry' ? this.digitalIndustryOptions :
                           type === 'digital_scenarios' ? this.digitalScenariosOptions : [];
            const item = options.find(item => item.dictValue === value);
            return item?.dictLabel || value;
        },
        initDigitalOptions() {
            for (const item of Object.values(this.commonDict)) {
                if (item.dictType === 'sme_digital_subtype') {
                    this.digitalSubtypeOptions = item.dictData;
                }
                if (item.dictType === 'sme_digital_industry') {
                    this.digitalIndustryOptions = item.dictData;
                }
                if (item.dictType === 'sme_digital_scenarios') {
                    this.digitalScenariosOptions = item.dictData;
                }
            }
        }
    }
}
</script>

<style scoped lang="scss">
@import "@/assets/css/element-variables";
/* Add your component styles here */
.rich-text-content {
  :deep(img) {
    max-width: 100%;
    height: auto;
    overflow: auto;
  }
}
.badge{
    top: 4px;
    right: 10px;
}
.button3{
    border-radius: 5px 5px 5px 5px;
    border: 1px solid #436AF7;
    background: #fff;
    color: #436AF7;
}
.companyContain{
    display: flex;
    padding-bottom: 15px;
    border-bottom: 1px solid #d8d8d8;
}
.detailContainer{
    margin: 0 auto;
    padding: 20px 15%;
    min-width: 1750px;
}
.comTile{
    font-size: 16px;
    font-family: MicrosoftYaHei;
    color: #333333;
    margin-bottom: 18px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 185px;
}
.carousel-image{
    width: 100%;
    height: 300px;

}
.smallIcon{
    width: 88px;
    height: 88px;
}
.quancard{
    width: 100%;
    height: 90px;
    background-image: url('@/assets/image/smallCoupon.png');
    background-size: 100% 100%;
    padding-left: 18%;
}
.quancard1{
    width: 100%;
    height: 90px;
    background-image: url('@/assets/image/smallCoupon1.png');
    background-size: 100% 100%;
    padding-left: 18%;
}
.custom-card{
    box-sizing: border-box;
    border-radius: 4px 4px 0px 0px;
    background: #fff;
}
.product-title{
    font-size: 24px;
    font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
    font-weight: bold;
    color: #333333;
    line-height: 31px;
    margin-bottom: 10px;
}
.custom-card-title{
    height: 48px;
    background: #f7f7f7;
    line-height: 48px;
    padding-left: 22px;
    font-size: 16px;
    font-family: MicrosoftYaHei;
    color: #333333;
    border-bottom: 1px solid #d8d8d8;
}
.button1{
    height: 40px;
    background: rgba(67, 106, 247,0.2);
    color:#436AF7 ;
    border-radius: 5px 5px 5px 5px;
    border: 1px solid #CFCFCF;
}
.button2{
    height: 40px;
    background: #436AF7;
    border-radius: 5px 5px 5px 5px;
    border: 1px solid #436AF7;
    margin-left: 40px;
}
.left-border{
    border-left: 3px solid #436AF7;
}
::v-deep.el-carousel__container{
    width: 100%;
    height: 270px;
}
::v-deep.carousel-image{
    width: 100%;
    height: 270px;
}
:deep(.el-tabs__nav-scroll) {
 padding-left: 40px;
}

:deep(.el-tabs--border-card .el-tabs__nav-scroll) {
 padding-left: 0;
}

:deep(.el-tabs__item.is-active) {
font-weight: bold;
}

:deep(.el-tabs__active-bar) {
 background-color: $--color-primary;
}
:deep(.el-tab-pane) {
min-height: 300px;
}
</style>